package com.ucap.wsbs.api;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.ucap.util.Conts;
import com.ucap.util.DateTime;
import com.ucap.util.StringUtils;
import com.ucap.weixin.model.WxWsbsUser;
import com.ucap.wsbs.model.*;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/5/1.
 */
public class IndexApiController extends Controller {
    public String retPath;

    public void toIndex() {
        System.out.println("开始进入申报");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        System.out.println("wxUser"+wxUser);
        if (wxUser == null) {
            wxUser = WxWsbsUser.me.findByOpenId("oFzs600J7ywRvvuD5y1rCcF-NL3E");
            setSessionAttr("wxUser", wxUser);
        }
        try {
            List<WxWsbsSbxx> sbxxList = WxWsbsSbxx.me.findByUserId(wxUser.get("id").toString());
            setAttr("sbxxList", sbxxList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        render("/WEB-INF/main/index.html");

    }

    public void toSb() {
        System.out.println("开始进入申报");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        String sblsh = getPara("sblsh");
        if (sblsh == null) {
            sblsh = getSessionAttr(Conts.WSBS_SBLSH);
        } else {
            setSessionAttr(Conts.WSBS_SBLSH, sblsh);
        }
        try {
            WxWsbsSbxx sbxx = null;
            if (sblsh != null) {
                sbxx = WxWsbsSbxx.me.findBySblsh(sblsh);
            }
            if (sbxx == null||sbxx.get("sbxx").toString().equals("1")) {
                sbxx = new WxWsbsSbxx();
                sbxx.set("id", StringUtils.getUUID());
                List<WxWsbsSbxx> sbxxList = WxWsbsSbxx.me.findLikeData();
                NumberFormat f = new DecimalFormat("00000");
                if (sbxxList == null || sbxxList.size() == 0) {
                    sbxx.set("sblsh", new DateTime().getDateTimeNYR() + f.format(1));
                } else {
                    sbxx.set("sblsh", new DateTime().getDateTimeNYR() + f.format(sbxxList.size() + 1));
                }
                sblsh = sbxx.get("sblsh");
                setSessionAttr(Conts.WSBS_SBLSH, sblsh);
                sbxx.set("userid", wxUser.get("id").toString());
                sbxx.set("addtime", new DateTime().getTimestamp());
                sbxx.set("adduser", Conts.getSessionUser(getSession()).get("id"));
                sbxx.set("updatetime", new DateTime().getTimestamp());
                sbxx.set("updateuser", Conts.getSessionUser(getSession()).get("id"));
                sbxx.set("datastate","I");
                sbxx.set("sbxx","0");
                sbxx.save();
            }
            setSessionAttr(Conts.WSBS_SBLSH, sbxx.get("sblsh"));
            setAttr("sbxx", sbxx);
            String step = getPara("step");

           /* if (sbxx == null||sbxx.get("sbxx").toString().equals("1")) {

            }*/
            //setSessionAttr(Conts.WSBS_SBLSH, sbxx.get("sblsh"));
            setAttr("sbxx", sbxx);


            switch (step) {
                case "qyxx":
                    WxWsbsQyxx qyxx = WxWsbsQyxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                    setAttr("data", qyxx);
                    retPath = "/WEB-INF/wsbs/qyxx.html";
                    break;
                case "frxx":

                    WxWsbsFrxx frxx = WxWsbsFrxx.me.findByUser(Conts.getSessionUser(getSession()).getStr("id"));
                    if (frxx == null) {
                        WxWsbsUserInfo  userInfo=WxWsbsUserInfo.me.findByOpenId(wxUser.get("openid").toString());
                        frxx = new WxWsbsFrxx();
                        frxx.set("name",userInfo.get("name"));
                        frxx.set("sex",userInfo.get("sex"));
                        frxx.set("nation",userInfo.get("nation")+"族");
                       // frxx.set("place",userInfo.get("id_address"));
                        frxx.set("detailedplace",userInfo.get("id_address"));
                        frxx.set("idtype",userInfo.get("1"));
                        frxx.set("phone",userInfo.get("phone"));
                        frxx.set("zjh",userInfo.get("idcard"));
                    }
                    qyxx = WxWsbsQyxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                    if (qyxx.get("qyxz").equals("1")) {
                        frxx.set("post", "负责人");
                    } else {
                        frxx.set("post", "法人");
                    }
                    setAttr("data", frxx);
                    retPath = "/WEB-INF/wsbs/frxx.html";
                    break;
                case "zzxx":
                    WxWsbsSbxx zzxx = WxWsbsSbxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                    List paras=new ArrayList();
                    paras.add("sfz");
                    paras.add(Conts.getWsbsSblsh(getSession()));
                    List<WxWsbsFile> sfzzmList = WxWsbsFile.me.findFileListBysblshAndTableName(paras);
                    if(sfzzmList==null||sfzzmList.size()<2){
                        WxWsbsUserInfo  userInfo=WxWsbsUserInfo.me.findByOpenId(wxUser.get("openid").toString());
                        createUpdateFile(userInfo.get("frontpic").toString(),"sfz");
                        createUpdateFile(userInfo.get("backpic").toString(),"sfz");
                        }


                    setAttr("data", zzxx);
                    retPath = "/WEB-INF/wsbs/zzxx.html";
                    break;
                case "sbxx":
                    sbxx = WxWsbsSbxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                    setAttr("data", sbxx);
                    retPath = "/WEB-INF/wsbs/sbxx.html";
                    break;

                case "spgly":
                    // WxWsbsSbxx sbpz=WxWsbsSbxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
                    setAttr("data", "11s");

                    retPath = "/WEB-INF/main/spgly.html";
                    break;
                default:
                    retPath = "/WEB-INF/wsbs/sbxx.html";
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        render(retPath);

    }
    public void toSbpz() {

        WxWsbsSbxx sbpz = WxWsbsSbxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));

        WxWsbsUser wxUser = getSessionAttr("wxUser");
        WxWsbsFrxx frxx = WxWsbsFrxx.me.findBySblsh(Conts.getWsbsSblsh(getSession()));
        String msgText="尊敬的"+frxx.get("name")+"先生/女士，您好！您已成功申请食品经营许可证网上全流程办理，申报流水号："+sbpz.get("sblsh")+"。办理结果我们将通过本公众号发送到您的微信上，敬请留意！详情请咨询：0769-22337223";
        ApiResult apiResult = CustomServiceApi.sendText(wxUser.get("openid").toString(), msgText);
        System.out.println("=====申报信息提示=====："+apiResult.toString());
        WxWsbsFile sbcl = WxWsbsFile.me.findSbclBySblsh(Conts.getWsbsSblsh(getSession()));
        removeSessionAttr(Conts.WSBS_SBLSH);
        setAttr("data", sbpz);
        setAttr("sbcl", sbcl);
        removeSessionAttr(Conts.WSBS_SBLSH);
        render("/WEB-INF/main/sbpz.html");
    }
    private void createUpdateFile(String imgStr, String tableName) {
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            String uploadPath = Conts.getSessionUser(getSession()).get("id").toString() + "/" + new DateTime().getYear() + "/" + new DateTime().getMonth() + "/" + new DateTime().getDay();
            System.out.println("生成jpeg图片"+uploadPath);
            String  imgFilePath= "/files/upload/" + uploadPath + "/" + System.currentTimeMillis()+".jpg";
            OutputStream out = new FileOutputStream(PathKit.getWebRootPath()+imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            File file=new File(PathKit.getWebRootPath()+imgFilePath);

            WxWsbsFile wsbsFile = new WxWsbsFile();
            wsbsFile.set("ID", StringUtils.getUUID());
            wsbsFile.set("SBLSH", Conts.getWsbsSblsh(getSession()));
            wsbsFile.set("USERID", Conts.getSessionUser(getSession()).get("id"));
            wsbsFile.set("FILEPATH",imgFilePath);
            wsbsFile.set("FILENAME", file.getName());
            wsbsFile.set("CONTENTTYPE","image/jpeg");
            wsbsFile.set("TABLENAME", tableName);
            wsbsFile.set("ADDTIME", new DateTime().getTimestamp());
            wsbsFile.set("ADDUSER", Conts.getSessionUser(getSession()).get("id"));
            wsbsFile.set("UPDATETIME", new DateTime().getTimestamp());
            wsbsFile.set("UPDATEUSER", Conts.getSessionUser(getSession()).get("id"));
            wsbsFile.set("DATASTATE", "I");

            JSONObject msg = new JSONObject();

            boolean boo = wsbsFile.save();
            msg.put("success", boo);
            if (boo) {
                msg.put("msg", "上传材料成功");
            } else {

                msg.put("msg", "上传材料失败");
            }
            msg.put("data", wsbsFile);
        }catch (Exception e){

e.printStackTrace();
        }
    }

    public void toWwcsbList() {
        System.out.println("开始进入申报");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        try {
            List<WxWsbsSbxx> sbxxList = WxWsbsSbxx.me.findByUserId(wxUser.get("id").toString());
            setAttr("sbxxList", sbxxList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        render("/WEB-INF/wsbs/wwcsb-list.html");

    }

    public void toSbList() {
        System.out.println("开始进入申报");
        WxWsbsUser wxUser = getSessionAttr("wxUser");
        try {
            List<WxWsbsSbxx> sbxxList = WxWsbsSbxx.me.findAllByUserId(wxUser.get("id").toString());
            setAttr("sbxxList", sbxxList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        render("/WEB-INF/wsbs/sbxx-list.html");

    }
}
